//
//  EntertainmentDetailsViewController.m
//  xxxx
//
//  Created by 我爱的妞 on 15/11/8.
//  Copyright © 2015年 @@叶一闽. All rights reserved.
//

#import "EntertainmentDetailsViewController.h"
#import "EnterCollectionViewCell.h"
#import "AppTools.h"
#import "XJCVideoModel.h"
#import "UIImageView+WebCache.h"
#import "XJCVideoPlayViewController.h"
#import "CoreDataManager.h"
#import "VideoModel.h"
#import "MBProgressHUD+show.h"
#import "MusicDetailViewController.h"
#import "DownloadViewController.h"
//#import "UMSocial.h"

@interface EntertainmentDetailsViewController () <UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) UIButton *playBtn;

@property (nonatomic, strong) UIScrollView *descScrollView;

@property (nonatomic, strong) UIView *headerView;

@property (nonatomic, assign) NSInteger urlIndex;

@property (nonatomic, assign) NSInteger bgIndex;

@property (nonatomic, assign) CGFloat currentX;

@property (nonatomic, assign) BOOL isPage;

@property (nonatomic, assign) NSInteger currentIndex;

@property (nonatomic, strong) UIView *bgView;

@property (nonatomic, strong) UIButton *collectBtn;

@property (nonatomic, strong) UIButton *downloadBtn;

@property (nonatomic, strong) UIButton *shareBtn;

@property (nonatomic, strong) UIImageView *collectView;

@property (nonatomic, strong) UIImageView *deleteView;

@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, strong) UILabel *downLabel;

@end

@implementation EntertainmentDetailsViewController

- (void)dealloc{
    NSLog(@"sss");
    
    if (_timer != nil) {
        [_timer invalidate];
        _timer = nil;
    }
    
}
- (void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = YES;
    NSInteger index = self.collectionView.contentOffset.x / WIDTH;
    XJCVideoModel *xjcModel = [_dataArray objectAtIndex:index];
    //查询
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"VideoModel"];
    NSArray *resultArray = [[CoreDataManager shareManager].managedObjectContext executeFetchRequest:request error:nil];
    for (VideoModel *model in resultArray) {
        if ([model.title isEqualToString:xjcModel.title]) {
            self.collectBtn.selected = YES;
        }
    }

    [super viewWillAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _currentIndex = 0;
    
    self.view.backgroundColor = [UIColor clearColor];
    
    //轻扫手势
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeAction:)];
    //轻扫方向
    swipe.direction = UISwipeGestureRecognizerDirectionUp;
    [self.view addGestureRecognizer:swipe];
    
    _currentX = 0;
    _bgIndex = 0;
    self.isPage = NO;
    
    self.bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 379 * SCALEH, WIDTH, 288 * SCALEH)];
    
    self.bgView.backgroundColor = [UIColor blackColor];
    
    [self.view addSubview:_bgView];
    
    self.descScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 379 *SCALEH, WIDTH, 288 *SCALEH)];
    self.descScrollView.backgroundColor = [UIColor grayColor];
    self.descScrollView.contentSize = CGSizeMake(10000000000, 0);

    [self.view addSubview:self.descScrollView];
    
    self.titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(20 * SCALEW, 399 *SCALEH, 0, 0)];
    //    self.titleLabel.backgroundColor = [UIColor colorWithRed:0.369 green:1.000 blue:0.713 alpha:1.000];
    self.titleLabel.font = [UIFont systemFontOfSize:17 * SCALEH];
    self.titleLabel.textColor = [UIColor whiteColor];
    
    self.lineView = [[UIView alloc]initWithFrame:CGRectMake(self.titleLabel.frame.origin.x, self.titleLabel.frame.origin.y + self.titleLabel.frame.size.height, 0, 0)];
    self.lineView.backgroundColor = [UIColor whiteColor];
    
    self.timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.titleLabel.frame.origin.x, _lineView.frame.origin.y+10, 0, 0)];
    self.timeLabel.font = [UIFont systemFontOfSize:15 *SCALEH];
    self.timeLabel.textColor = [UIColor whiteColor];
    
    self.descLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.titleLabel.frame.origin.x, self.timeLabel.frame.origin.y + self.timeLabel.frame.size.height , 0, 0)];
    self.descLabel.textColor = [UIColor whiteColor];
//            self.descLabel.backgroundColor = [UIColor colorWithRed:0.893 green:1.000 blue:0.406 alpha:1.000];
    self.descLabel.font = [UIFont systemFontOfSize:14 * SCALEH];
    self.descLabel.numberOfLines = 0;
    
    self.collectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.collectBtn.frame = CGRectMake(self.titleLabel.frame.origin.x, 600 * SCALEH, 20 * SCALEW, 20 * SCALEW);
    [self.collectBtn setImage:[UIImage imageNamed:@"iconfont-xihuan.png"] forState:UIControlStateNormal];
    [self.collectBtn setImage:[UIImage imageNamed:@"iconfont-xihuanjiaohu.png"] forState:UIControlStateSelected];
    [self.collectBtn addTarget:self action:@selector(collectAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.shareBtn.frame = CGRectMake(self.titleLabel.frame.origin.x + 100 * SCALEW, self.collectBtn.frame.origin.y, self.collectBtn.frame.size.width, self.collectBtn.frame.size.height);
    [self.shareBtn setImage:[UIImage imageNamed:@"iconfont-fenxiang-2.png"] forState:UIControlStateNormal];
    [self.shareBtn addTarget:self action:@selector(shareAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.downloadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.downloadBtn.frame = CGRectMake(self.shareBtn.frame.origin.x + 100 * SCALEW, self.collectBtn.frame.origin.y, self.collectBtn.frame.size.width, self.collectBtn.frame.size.height);
    [self.downloadBtn setImage:[UIImage imageNamed:@"iconfont-iconfontxiazai.png"] forState:UIControlStateNormal];
    [self.downloadBtn addTarget:self action:@selector(downloadAction) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *collectLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.collectBtn.frame.origin.x + self.collectBtn.frame.size.width + 3, self.collectBtn.frame.origin.y, 50 * SCALEW, self.collectBtn.frame.size.height)];
    collectLabel.text = @"喜欢";
    collectLabel.textColor = [UIColor whiteColor];
    collectLabel.font = [UIFont  systemFontOfSize:15 * SCALEH];
    
    UILabel *shareLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.shareBtn.frame.origin.x + self.shareBtn.frame.size.width + 3, self.collectBtn.frame.origin.y, 50 * SCALEW, self.collectBtn.frame.size.height)];
    shareLabel.text = @"分享";
    shareLabel.textColor = [UIColor whiteColor];
    shareLabel.font = [UIFont  systemFontOfSize:15 * SCALEH];
    
    UILabel *downloadLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.downloadBtn.frame.origin.x + self.downloadBtn.frame.size.width + 3, self.collectBtn.frame.origin.y, 50 * SCALEW, self.collectBtn.frame.size.height)];
    downloadLabel.text = @"下载";
    downloadLabel.textColor = [UIColor whiteColor];
    downloadLabel.font = [UIFont  systemFontOfSize:15 * SCALEW];
    
    self.downLabel = downloadLabel;
    
    [self.view addSubview:self.titleLabel];
    [self.view addSubview:self.lineView];
    [self.view addSubview:self.timeLabel];
    [self.view addSubview:self.descLabel];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumInteritemSpacing = 0;
    //设置列间距
    flowLayout.minimumLineSpacing = 0;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    //设置item上左下右的边界距离
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView.pagingEnabled = YES;
    
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.bounces = NO;
    
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView"];
    //注册cell
    [self.collectionView registerClass:[EnterCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    
    self.playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [_playBtn setImage:[UIImage imageNamed:@"iconfont-bofang.png"] forState:UIControlStateNormal];
    
    self.playBtn.frame = CGRectMake(0, 0, 60 * SCALEW, 60 * SCALEW);
    self.playBtn.center = CGPointMake(WIDTH / 2, (315 + 64 * 2) / 2 * SCALEW);
    self.playBtn.alpha = 0;
    [self.playBtn addTarget:self action:@selector(playAction) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.playBtn];
    
    self.currentIndex = self.dataArray.count;
    
    _tempImageView = [[UIImageView alloc] initWithFrame:self.rect];
    _tempImageView.image = _tempImage;
    
    [self.view addSubview:_tempImageView];
    
    CGRect rect = self.rect;
    rect.origin.y -= 64;

    self.descScrollView.frame = self.rect;
    self.bgView.frame = self.rect;
    [self initBGView];
    
    [UIView animateWithDuration:0.3 animations:^{
        
        self.tempImageView.frame = CGRectMake(-25 * SCALEW, 64, 425 *SCALEW, 315 * SCALEH);
        self.descScrollView.frame = CGRectMake(0, 379 * SCALEH, WIDTH, 288 * SCALEH);
        self.bgView.frame = CGRectMake(0, 379 * SCALEH, WIDTH, 288 * SCALEH);
        
    }completion:^(BOOL finished) {
        [self.tempImageView removeFromSuperview];
        [self.view addSubview:self.collectionView];
        [self.view addSubview:self.collectBtn];
        [self.view addSubview:self.shareBtn];
        [self.view addSubview:self.downloadBtn];
        [self.view addSubview:collectLabel];
        [self.view addSubview:shareLabel];
        [self.view addSubview:downloadLabel];
        self.playBtn.alpha = 1;
        [self.view bringSubviewToFront:self.playBtn];
    }];
    
}
//收藏事件
- (void)collectAction{

    NSInteger index = self.collectionView.contentOffset.x / WIDTH;
    XJCVideoModel *xjcModel = [_dataArray objectAtIndex:index];
    if (self.collectBtn.selected == NO) {
        //添加
        VideoModel *model = [NSEntityDescription insertNewObjectForEntityForName:@"VideoModel" inManagedObjectContext:[CoreDataManager shareManager].managedObjectContext];
        model.title = xjcModel.title;
        model.descrip = xjcModel.descrip;
        model.coverBlurred = xjcModel.coverBlurred;
        model.coverForFeed = xjcModel.coverForFeed;
        model.highUrl = xjcModel.playUrl;
        model.normalUrl = [[xjcModel.playInfo objectAtIndex:0] objectForKey:@"url"];
        model.date = xjcModel.date;
        
//        [MBProgressHUD showInfoWithText:@"收藏(ฅ>ω<*ฅ)成功"];
        [MBProgressHUD showCollectGIFWithText:@"收藏(ฅ>ω<*ฅ)成功"];
    }else{
        //查询然后删除
        NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"VideoModel"];
        NSArray *resultArray = [[CoreDataManager shareManager].managedObjectContext executeFetchRequest:request error:nil];
        for (VideoModel *model in resultArray) {
            if ([model.title isEqualToString:xjcModel.title]) {
                [[CoreDataManager shareManager].managedObjectContext deleteObject:model];
            }
        }
        [MBProgressHUD showGIFWithText:@"取消%>_<%收藏"];
    }
    
    [[CoreDataManager shareManager] saveContext];
    
    self.collectBtn.selected = !self.collectBtn.selected;
}
//分享事件
- (void)shareAction{

//    NSInteger index = self.collectionView.contentOffset.x / WIDTH;
//    XJCVideoModel *xjcModel = [_dataArray objectAtIndex:index];
//    [UMSocialSnsService presentSnsIconSheetView:self appKey:@"507fcab25270157b37000010"
//                                      shareText:xjcModel.playUrl
//                                     shareImage:xjcModel.coverForFeed
//                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToTwitter, nil]
//                                       delegate:self];
}
//下载事件
- (void)downloadAction{
    
    if ([_downLabel.text isEqualToString:@"已下载"]) {
        [MBProgressHUD showInfoWithText:@"该视频已下载"];
        return;
    }
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timeAction) userInfo:nil repeats:YES];
    
    NSInteger index = self.collectionView.contentOffset.x / WIDTH;
    XJCVideoModel *xjcModel = [_dataArray objectAtIndex:index];
    
    NSString *name = xjcModel.title;
    NSString *url = xjcModel.playUrl;
    
    [DownloadViewController shareDownloadHandle].titleStr = name;
    [DownloadViewController shareDownloadHandle].downUrl = url;
    
    [[DownloadViewController shareDownloadHandle] startDownload];
}

- (void)timeAction{
    NSLog(@"a");
    if ([DownloadViewController shareDownloadHandle].currentProgress == 1) {
        _downLabel.text = @"已下载";
        [MBProgressHUD showSuccessWithText:@"下载完成"];
        
        [_timer invalidate];
        return;
    }
    
    NSString *str = [NSString stringWithFormat:@"%.1f%%", [DownloadViewController shareDownloadHandle].currentProgress * 100];
    
    _downLabel.text = str;
}

- (void)hiddenBottomViews:(CGFloat)alpha{
    
    self.timeLabel.alpha = alpha;
    self.titleLabel.alpha = alpha;
    self.lineView.alpha = alpha;
    self.descLabel.alpha = alpha;
    
}

- (void)swipeAction:(UISwipeGestureRecognizer *)swipe{
    
    [self.collectionView removeFromSuperview];
    self.view.backgroundColor = [UIColor clearColor];
    NSInteger index = self.collectionView.contentOffset.x / WIDTH;
    self.playBtn.alpha = 0;
    self.descScrollView.contentOffset = CGPointMake(index * WIDTH, 0);
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
    
    EnterCollectionViewCell *cell = (EnterCollectionViewCell *)[_collectionView cellForItemAtIndexPath:indexPath];
    
    self.tempImageView.image = cell.imageView.image;
    self.view.backgroundColor = [UIColor clearColor];
    CGFloat y = self.rect.origin.y + 200 * SCALEH * (index - _contentSet);
    
    if (HEIGHT > y && 0 < y) {
        [self.delegate popMyController:0 andDataArray:_dataArray];
        _rect.origin.y = _rect.origin.y + ((index - _contentSet) * 200 * SCALEH);
    }else{
        NSLog(@"%ld", (index - _contentSet));
        [self.delegate popMyController:(index - _contentSet) andDataArray:_dataArray];
    }
    
    [UIView animateWithDuration:0.35 animations:^{
        
        self.descScrollView.frame = self.rect;
        [self.view addSubview:self.tempImageView];
        self.tempImageView.frame = self.rect;
        self.bgView.frame = self.rect;
        [self hiddenBottomViews:0];
        
    } completion:^(BOOL finished) {
        //动画结束时将当前页view和controller移除
        self.tabBarController.tabBar.hidden = NO;
        [self.view removeFromSuperview];
        [self removeFromParentViewController];

    }];
}

- (void)initBGView{
    
    
    NSInteger i = 0;
    for (XJCVideoModel *model in self.dataArray) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH * i, 0, WIDTH, 288*SCALEH)];
        [_descScrollView addSubview:imageView];
        [imageView sd_setImageWithURL:[NSURL URLWithString:model.coverBlurred] placeholderImage:nil];
        
        i++;
    }
    

    [self.descScrollView bringSubviewToFront:_bgView];


}

- (void)afnGetData{
    NSString *http = nil;
    
    if (self.type == 0) {
        http = [NSString stringWithFormat:@"http://baobab.wandoujia.com/api/v1/videos?start=%ld&num=10&categoryName=%%E6%%97%%85%%E8%%A1%%8C&strategy=date&vc=125&t=MjAxNTExMDkxNjE5MDQzNjUsNzM4NQ%%3D%%3D&u=8ec6699acd6fc4d031604939eac83d6c785eb50f&net=wifi&v=1.8.1&f=iphone", self.currentIndex];
    }else{
        http = [NSString stringWithFormat:@"http://baobab.wandoujia.com/api/v1/videos?start=%ld&num=10&categoryName=%%E6%%97%%85%%E8%%A1%%8C&strategy=shareCount&vc=125&t=MjAxNTExMDkxODU2NTUyNzcsNjM3NA%%3D%%3D&u=8ec6699acd6fc4d031604939eac83d6c785eb50f&net=wifi&v=1.8.1&f=iphone", self.currentIndex];
    }
    
    NSLog(@"sss%@", http);
    
    [AppTools getAFN:http andpara:nil andBlock:^(id result) {
        
        NSArray *array = [result objectForKey:@"videoList"];
        
        NSInteger i = self.dataArray.count;
        
        for (NSDictionary *dic in array) {
            
            XJCVideoModel *model = [[XJCVideoModel alloc] init];
            
            [model setValuesForKeysWithDictionary:dic];
            model.descrip = [dic objectForKey:@"description"];
            model.iD = [dic  objectForKey:@"id"];
            
            [self.dataArray addObject:model];
            
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH * i, 0, WIDTH, 288 * SCALEH)];
            
            [_descScrollView addSubview:imageView];
            
            [imageView sd_setImageWithURL:[NSURL URLWithString:model.coverBlurred] placeholderImage:nil];
            i++;
        }
        
        [self.descScrollView bringSubviewToFront:_bgView];
        self.currentIndex = self.dataArray.count;
        [self.collectionView reloadData];

    } andfailBlock:^(id result) {
        NSLog(@"error");
    }];
    
}

- (void)setDataArray:(NSMutableArray *)dataArray{
    
    _dataArray = dataArray;
    _currentIndex = dataArray.count;

}

- (void)setContentSet:(NSInteger)contentSet{
    
    _contentSet = contentSet;
    NSLog(@"#%ld",contentSet);
    self.collectionView.contentOffset = CGPointMake(contentSet * WIDTH, 0);
    self.descScrollView.contentOffset = CGPointMake(contentSet * WIDTH, 0);
    
    
    if (contentSet >= self.dataArray.count - 2) {
        [self afnGetData];
    }
    XJCVideoModel *model = [self.dataArray objectAtIndex:contentSet];
    //赋值
    self.titleLabel.text = model.title;
    NSLog(@"~%@",self.titleLabel.text);
    self.descLabel.text = model.descrip;
    
    NSString *str1 = @"#";
    NSString *str2 = [str1 stringByAppendingString:@"旅行  /  "];
    int x =  [model.duration intValue];
    NSString *str3 = [NSString stringWithFormat:@"%d",x/60];
    NSString *str4 = [NSString stringWithFormat:@"%d",x%60];
    if (x/60 >= 10) {
        if (x % 60 >= 10) {
            NSString *str5 = [[[[str2 stringByAppendingString:str3]stringByAppendingString:@"'"]stringByAppendingString:str4]stringByAppendingString:@"''"];
            self.timeLabel.text = str5;
        }else{
            NSString *str5 = [[[[[str2 stringByAppendingString:str3]stringByAppendingString:@"'"] stringByAppendingString:@"0"]stringByAppendingString:str4]stringByAppendingString:@"''"];
            self.timeLabel.text = str5;
        }
        
    }else{
        if (x % 60 >= 10) {
            NSString *str5 = [[[[[str2 stringByAppendingString:@"0"] stringByAppendingString:str3]stringByAppendingString:@"'"]stringByAppendingString:str4]stringByAppendingString:@"''"];
            self.timeLabel.text = str5;
        }else{
            NSString *str5 = [[[[[[str2 stringByAppendingString:@"0"] stringByAppendingString:str3]stringByAppendingString:@"'"] stringByAppendingString:@"0"]stringByAppendingString:str4]stringByAppendingString:@"''"];
            self.timeLabel.text = str5;
        }
        
    }
    [UIView animateWithDuration:0.8 animations:^{
        
        CGFloat width = [AppTools widthForLabel:self.titleLabel.text and:18 andHeight:50*SCALEH];
        self.titleLabel.frame = CGRectMake(20*SCALEW, 399*SCALEH, width, 50*SCALEH);
        self.lineView.frame = CGRectMake(20*SCALEW, 449*SCALEH, self.titleLabel.frame.size.width - 40*SCALEW, 1);
        self.descLabel.frame = CGRectMake(20*SCALEW, 470*SCALEH , WIDTH - 2 * 20*SCALEW, 100 * SCALEH);
        self.timeLabel.frame = CGRectMake(20*SCALEW, 459*SCALEH, WIDTH - 20*SCALEW - 50*SCALEW, 15*SCALEH);
        self.timeLabel.alpha = 1;
        self.titleLabel.alpha = 1;
        self.lineView.alpha = 1;
        self.descLabel.alpha = 1;
        
    }];
    
    [self searchFile];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    //直接从重用池里取
    EnterCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    XJCVideoModel *model = [_dataArray objectAtIndex:indexPath.row];
    cell.model = model;
    cell.backgroundColor = [UIColor clearColor];
    
    return cell;
}

- (void)playAction{
    //视频播放时音乐播放暂停
    [[MusicDetailViewController sharePlayerViewController].player stop];
    
    XJCVideoPlayViewController *videoPlayVC = [[XJCVideoPlayViewController alloc] init];
    NSInteger index = self.collectionView.contentOffset.x / WIDTH;
    XJCVideoModel *videoModel = [_dataArray objectAtIndex:index];

    videoPlayVC.videoModel = videoModel;
    videoPlayVC.videoModelArray = _dataArray;
    [self presentViewController:videoPlayVC animated:YES completion:nil];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    CGFloat content = scrollView.contentOffset.x;
    
    self.currentX = content;
    
    if (content >= 0 && content <= scrollView.contentSize.width - [UIScreen mainScreen].bounds.size.width) {
        
        NSIndexPath *contentIndexPath = [NSIndexPath indexPathForItem:scrollView.contentOffset.x / [UIScreen mainScreen].bounds.size.width inSection:0];
        NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem:scrollView.contentOffset.x / [UIScreen mainScreen].bounds.size.width + 1 inSection:0];
        
        EnterCollectionViewCell *contentCell = (EnterCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:contentIndexPath];
        EnterCollectionViewCell *nextCell = (EnterCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:nextIndexPath];
        
        CGRect contentImageViewRect = contentCell.imageView.frame;
        CGRect nextImageViewRect = nextCell.imageView.frame;
        contentImageViewRect.origin.x = 0 + (content - contentIndexPath.item * [UIScreen mainScreen].bounds.size.width) / 1.5;
        nextImageViewRect.origin.x = 0 - [UIScreen mainScreen].bounds.size.width / 1.5 + (content - contentIndexPath.item * [UIScreen mainScreen].bounds.size.width) / 1.5;
        contentCell.imageView.frame = contentImageViewRect;
        nextCell.imageView.frame = nextImageViewRect;
        
        CGFloat alpha = fabs(1 - (scrollView.contentOffset.x / WIDTH - contentIndexPath.row) * 2);
        self.descScrollView.alpha = alpha + 0.2;
        
        NSInteger xIndex = (content + WIDTH / 2) / WIDTH;
        CGPoint point = scrollView.contentOffset;
        point.x = xIndex * WIDTH;
        self.descScrollView.contentOffset = point;
        self.playBtn.alpha = alpha;
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    [self searchFile];
    
    NSInteger index = scrollView.contentOffset.x / WIDTH;
    if (index == self.dataArray.count - 2) {
        
        [self afnGetData];
        
    }
    XJCVideoModel *model = [_dataArray objectAtIndex:index];
    
    //赋值
    self.titleLabel.text = model.title;
    NSLog(@"~%@",self.titleLabel.text);
    self.descLabel.text = model.descrip;
    NSLog(@"description = %@",model.descrip);
    /**时间字符串**/
    NSString *str1 = @"#";
    NSString *str2 = [str1 stringByAppendingString:@"旅行  /  "];
    int x =  [model.duration intValue];
    NSString *str3 = [NSString stringWithFormat:@"%d",x/60];
    NSString *str4 = [NSString stringWithFormat:@"%d",x%60];
    if (x/60 >= 10) {
        if (x % 60 >= 10) {
            NSString *str5 = [[[[str2 stringByAppendingString:str3]stringByAppendingString:@"'"]stringByAppendingString:str4]stringByAppendingString:@"''"];
            self.timeLabel.text = str5;
        }else{
            NSString *str5 = [[[[[str2 stringByAppendingString:str3]stringByAppendingString:@"'"] stringByAppendingString:@"0"]stringByAppendingString:str4]stringByAppendingString:@"''"];
            self.timeLabel.text = str5;
        }
        
    }else{
        if (x % 60 >= 10) {
            NSString *str5 = [[[[[str2 stringByAppendingString:@"0"] stringByAppendingString:str3]stringByAppendingString:@"'"]stringByAppendingString:str4]stringByAppendingString:@"''"];
            self.timeLabel.text = str5;
        }else{
            NSString *str5 = [[[[[[str2 stringByAppendingString:@"0"] stringByAppendingString:str3]stringByAppendingString:@"'"] stringByAppendingString:@"0"]stringByAppendingString:str4]stringByAppendingString:@"''"];
            self.timeLabel.text = str5;
        }
        
    }

    CGFloat width = [AppTools widthForLabel:self.titleLabel.text and:18 * SCALEH andHeight:50*SCALEH];
    self.titleLabel.frame = CGRectMake(20*SCALEW, 399*SCALEH, width, 50*SCALEH);
    self.lineView.frame = CGRectMake(20*SCALEW, 449*SCALEH, self.titleLabel.frame.size.width - 40*SCALEW, 1);
    self.descLabel.frame = CGRectMake(20*SCALEW, 470*SCALEH , WIDTH - 2 * 20*SCALEW, 100);
    self.timeLabel.frame = CGRectMake(20*SCALEW, 459*SCALEH, WIDTH - 20*SCALEW - 50*SCALEW, 15*SCALEH);
    
    CGPoint point = scrollView.contentOffset;
    
    self.descScrollView.contentOffset = point;
    
}

- (void)searchFile{
    
    NSInteger index = self.collectionView.contentOffset.x / WIDTH;
    
    XJCVideoModel *model = [_dataArray objectAtIndex:index];
    
    if ([[DownloadViewController shareDownloadHandle].titleStr isEqualToString:model.title]) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timeAction) userInfo:nil repeats:YES];
        self.downLabel.text = @"下载中";
        [_timer fire];
        
        return;
    }else{
        
        if (_timer != nil) {
            [_timer invalidate];
        }
    }
    
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    NSString *pathDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *createPath = [NSString stringWithFormat:@"%@/Image", pathDocuments];
    NSArray  *array = [fileManager directoryContentsAtPath:createPath];
    
    NSString *str2 = [NSString stringWithFormat:@"%@.mp4", model.title];
    
    for (NSString *str in array) {
        
        if ([str isEqualToString:str2]) {
            self.downLabel.text = @"已下载";
            return;
        }
    }
    
    self.downLabel.text = @"下载";
}

//设置大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return CGSizeMake(WIDTH, HEIGHT);
}

@end
